Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.YSEQEntry = function() {

    var entryPanel = null;
    var entryForm = null;
    var entryLoaded = false;
    var sampleGrid = null;
    var yseqCount = 0;
    var yseqOligoCount = 0;
    var yseqRADCount = 0;
    var yseqMaxNum = 0;
    var yseqHash = null;
    var sequencingStore = null;
    var sequencingHash = null;
    var mySequencingData = [];
    var now = new Date();
    var submittedDateDef = now.format("m/d/Y");
    var initData = [];
    var sampleAliasArray = [];
    var createNew = false;
    var selectedSeqRec = {};
    var searchInput = '*';
    var searchOption = 'All';
    var pagingBar = null;
    var spotlightMenu = sptlght.utils.SpotlightUtils.getSpotlightMenu("yseqspotlightmenuid");

    var promptRadWin = {};
    var radBarcodeJson = {};
    var rangeYPGJson = {};
    var radYcrJson = {};
    var initGenData = [];
    var grptWin = null;

    var kwin = new Ext.Window({
        title: 'Processing...',
        width: 400,
        minWidth: 350,
        height: 150,
        modal: true,
        closeAction: 'hide',
        bodyStyle: 'padding:10px;',
        html: "RAD Data Loading...",
        bbar: new Ext.ux.StatusBar({
            id: 'init-rad-statusbar',
            defaultText: 'Processing...'
        })
    });
    kwin.on("show", function () {
        var sb = Ext.getCmp("init-rad-statusbar");
        sb.showBusy();
    });
    Ext.QuickTips.init();

    function getDudleyProjectCombo(hashObj) {
        var dudleyProjectStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : getDudleyProjectArray()
        });
        var dudleyProjectCombo = new Ext.form.ComboBox({
            store: dudleyProjectStore,
            id: 'yseqProject',
            fieldLabel: 'Project',
            displayField:'value',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            value:hashObj.dudleyProject,
            forceSelection:true,
            selectOnFocus:true
        });
        dudleyProjectCombo.on("select", function (c, r, i) {
            var sampleTextArea = Ext.getCmp("yseqSamples");
            if (sampleTextArea != null) {
                var samplePrepCombo = Ext.getCmp("yseqSamplePrep");
                if ((i == 4 || i == 1) && createNew) {
                    var radSampleFileField = Ext.getCmp("yseqRadSampleFileId");
                    radSampleFileField.enable();
                    if (i == 1) {
                        var yseqRADCount_next = parseInt(yseqRADCount) + 1;
                        sampleTextArea.setValue("YMULTI_RAD_" + yseqRADCount_next);
                        samplePrepCombo.setValue("Genomic DNA Multiplex RAD");
                        var instrument = Ext.getCmp("yseqInstrument").getValue();
                        Ext.getCmp("yseqAdaptorKit").setValue(instrument + " RAD");
                        Ext.getCmp("yseqShearMethod").setValue("Restriction Enzyme");
                        initData[0] = ["YMULTI_RAD_" + yseqRADCount_next,"New",submittedDateDef,,''];
                        ds.loadData(initData);
                        loadSampleGrid(yseqHash.name, ds, createNew);
                    } else {
                        radSampleFileField.disable();
                        var yseqOligoCount_next = parseInt(yseqOligoCount) + 1;
                        sampleTextArea.setValue("YOligo_Pilot_" + yseqOligoCount_next);
                        samplePrepCombo.setValue("Small RNA");
                        var seqState = yseqHash.yseqState;
                        if (seqState == 'New' || seqState == 'Draft') {
                            validateSamples(0, null, initData, false, function () {
                                ds.loadData(initData);
                                loadSampleGrid(hashObj.name, ds, createNew);
                            });
                        }
                    }
                }
            }
        });
        return dudleyProjectCombo;
    }

    function getSamplePrepCombo(hashObj) {
        var samplePrepStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : getSamplePrepArray()
        });
        var samplePrepCombo = new Ext.form.ComboBox({
            store: samplePrepStore,
            id: 'yseqSamplePrep',
            fieldLabel: 'Library prep kit',
            displayField:'value',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            value:hashObj.samplePrep,
            forceSelection:true,
            width:220,
            selectOnFocus:true
        });
        samplePrepCombo.on("select", function (c, r, i) {
            if (((i >= 9 && i < 11) || i == 4) && createNew) {
                var dudleyProject = Ext.getCmp("yseqProject");
                var sampleTextArea = Ext.getCmp("yseqSamples");
                if (sampleTextArea != null) {
                    if (i >= 9) {
                        var yseqRADCount_next = parseInt(yseqRADCount) + 1;
                        sampleTextArea.setValue("YMULTI_RAD_" + yseqRADCount_next);
                        dudleyProject.setValue("Dudley NV Multiplex RAD");
                        Ext.getCmp("yseqRadSampleFileId").enable();
                        initData[0] = ["YMULTI_RAD_" + yseqRADCount_next,"New",submittedDateDef,,''];
                        ds.loadData(initData);
                        loadSampleGrid(yseqHash.name, ds, createNew);
                    } else {
                        var yseqOligoCount_next = parseInt(yseqOligoCount) + 1;
                        sampleTextArea.setValue("YOligo_Pilot_" + yseqOligoCount_next);
                        var seqState = yseqHash.yseqState;
                        if (seqState == 'New' || seqState == 'Draft') {
                            validateSamples(0, null, initData, false, function () {
                                ds.loadData(initData);
                                loadSampleGrid("", ds, createNew);
                            });
                        }
                    }
                } else {
                    sampleTextArea.setDisabled(false);
                    var radSampleFileField = Ext.getCmp("radSampleFileId");
                    if (radSampleFileField)
                        radSampleFileField.setDisabled(true);
                }
            }
        });
        return samplePrepCombo;
    }
    Ext.form.Field.prototype.msgTarget = 'side';
    var messageContextMenu = new Ext.menu.Menu({
        id: 'messageContextMenu',
        items: [
            {
                text: 'Open',
                handler: onMessageContextItemClick
            },
            {
                text: 'Print',
                handler: onMessageContextItemClick
            },
            '-',
            {
                text: 'Reply',
                handler: onMessageContextItemClick
            },
            {
                text: 'Not Spam',
                handler: onMessageContextItemClick
            },
            '-',
            {
                text: 'Properties',
                handler: onMessageContextItemClick
            }
        ]
    });

    var ds = new Ext.data.Store({
        reader: new Ext.data.ArrayReader({}, [
            {
                name: 'name'
            },
            {
                name: 'status'
            },
            {
                name: 'statusDate',
                type: 'date'
            },
            {
                name: 'flowcell'
            },
            {
                name: 'lane'
            },
            {
                name: 'comment'
            }
        ]),
        sortInfo: {field:'name', direction:'ASC'}
    });
    resetSampleStore();

    function resetSampleStore() {
        ds.loadData(initData);
    }

    var colModel = new Ext.grid.ColumnModel([
        {
            id:'name',
            header: "Sample",
            width: 100,
            sortable: true,
            locked:false,
            dataIndex: 'name'
        },
        {
            header: "Status",
            width: 70,
            sortable: true,
            dataIndex: 'status'
        },
        {
            header: "Date",
            width: 65,
            sortable: true,
            renderer: Ext.util.Format.dateRenderer('m/d/Y'),
            dataIndex: 'statusDate'
        },
        {
            header: "Flowcell",
            width: 80,
            sortable: true,
            dataIndex: 'flowcell'
        },
        {
            header: "Lane",
            width: 40,
            sortable: true,
            dataIndex: 'lane'
        },
        {
            header: "Comment",
            width: 100,
            sortable: true,
            dataIndex: 'comment'
        }
    ]);

    var searchAllUrl = getSolrSearchUrl("yseqKey:yseq", 1000, sequencingFields);
    //getSolrSearchUrlgetSequencingSearchUrl("FREE_TEXT=*", "", "");

    function onMessageContextItemClick(item) {
        alert("item:" + item);
    }

    function initYSEQStore(callback) {
        Ext.Ajax.request({
            url: searchAllUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                loadSequencingSearchResult(0, searchResultObj.response, callback);
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Initial load failed for sequencing:" + searchAllUrl, level: "error" });
            }
        });
    }

    function loadSequencingSearchResult(index, searchResultJSON, callback) {
    	seqRptArray = [];
	sequencingStore = loadSolrSearchResult("YSEQ", getSequencingPagingColumns(), sequencingSolrTranslator, index, searchResultJSON);
        sequencingStore.load({params:{start:0, limit:10}}, callback());
    }

    function goSearch(index, seqSearchInput, seqSearchOption) {
    	var searchUrl = getSolrSearchUrl(seqSearchOption + ":" + seqSearchInput, 1000, sequencingFields);
        var searchWin = getSearchLoadingWindow("yseq-");                
        searchWin.on("show", function () {
            var sb = Ext.getCmp("yseq-search-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                eventManager.fireStatusMessageEvent({ text: "Sequencing Search Results Count:" + searchResultObj.response.numberOfResults, level: "info" });
                mySequencingData = [];
                ds.removeAll();
                loadSequencingSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("yseq-search-results").innerHTML = "";
                    Ext.getDom("wo-form").innerHTML = "";
                    searchWin.close();
                    renderSequencingSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadEntryPanel() {
        sampleGrid = loadSampleGrid("", ds, true);
        var advancedSearchLink = '<A HREF="javascript:Dudley.lims.samplemgr.renderAdvancedSearch(\'' + "YEQ" + '\')">' + 'Advanced' + '</A>';
        var sequencingSearchForm = getSearchForm("sequencingSearchButtonId", "sequencingSearchInputId", advancedSearchLink);
        Ext.getCmp("sequencingSearchButtonId").addListener("click", function(){
			goSearch(0, Ext.getCmp("sequencingSearchInputId").getValue(), "yseqFields");		
		});
		var tbarButtons = [
            {
                id: 'showYseqSearchResultsId',
                disabled: true,
                text: 'Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("wo-form").innerHTML = "";
                            renderSequencingSearchResult();
                        }
                }
            },
            {
                id: 'searchAllSequencingId',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("wo-form").innerHTML = "";
                            goSearch(0, '*', 'yseqKey');
                        }
                }
            },
            {
                id: 'createNewEntryId',
                text: 'New Run',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            createNew = true;
                            ds.removeAll();
                            Dudley.lims.YSEQEntry.loadNewEntry();
                        }
                }
            }
        ];
        entryPanel = new Ext.Panel({
            id: "seqEntryPanelId",
            autoHeight: true,
            border: true,
            autoScroll: true,
            renderTo: "entry-panel",
            title: "NextGen-Sequencing",
            header: false,
            tbar: tbarButtons,
            items: sequencingSearchForm
        });
        entryPanel.on("activate", function () {
            Ext.getDom("cgs-panel").innerHTML = "";
            Dudley.lims.sequencingmgr.clearPane();
            if (!entryLoaded && !Dudley.lims.sequencingmgr.getSeqLoaded()) {
                entryLoaded = true;
                goSearch(0, "*", "yseqKey");
            }
            renderSequencingSearchResult();
        });
    }

    /*
     Recursively call itself to validate each sample, then adding the sample to the list
     */
    function validateSamples(i, sampleList, storeList, notMultiplex, callback) {
        if (notMultiplex) {
            var len = sampleList.length;
            if (sampleList[i]) {
                var mySample = sampleList[i];// + " " + sampleList[i + 1];
                mySample = mySample.toUpperCase();
                //replace url with SOLR search
                var sampleUrl = "";///solr/addama-rest/dudley-sample/path/datasource/" + sampleList[i].toUpperCase() + "/" + mySample + "/annotations";
                if (sampleList[i].toUpperCase().indexOf("YO") != -1){
                    sampleUrl = getSolrSearchUrl("yoKey:" + mySample, 1, yoFields);
                }else if (sampleList[i].toUpperCase().indexOf("YAD") != -1){
                    sampleUrl = getSolrSearchUrl("yadKey:" + mySample, 1, yadFields);
                }else if (sampleList[i].toUpperCase().indexOf("YPG") != -1){
                    sampleUrl = getSolrSearchUrl("ypgKey:" + mySample, 1, ypgFields);
                }
               // var sampleUrl = "/addama-rest/dudley-sample/path/datasource/" + sampleList[i].toUpperCase() + "/" + mySample + "/annotations";
                //sampleUrl = sampleUrl.replace(/ /g, "%20");
                Ext.Ajax.request({
                    url: sampleUrl,
                    method: "GET",
                    success: function(response) {
                        var resp = Ext.util.JSON.decode(response.responseText);
                        var annotationsObj = resp.response.docs[0];
                        var aliasKey = "yoAlias";
                        if (sampleUrl.indexOf("yadKey") != -1){
                            aliasKey = "yadAlias";
                        }else if (sampleUrl.indexOf("ypgKey") != -1){
                            aliasKey = "ypgAlias";
                        }
                        var alias = "n/a"
                        if (annotationsObj[aliasKey]){
                            alias = annotationsObj[aliasKey];
                        }
                        for (var s = 0; s < storeList.length; s++) {
                            if (mySample == storeList[s][0]) {
                                storeList = [];
                                Ext.MessageBox.alert("Please fix sample entries; Duplicated amples are not allowed on the same sequence run:" + mySample);
                                eventManager.fireStatusMessageEvent({ text: "Duplicated amples are not allowed on the same sequence run:" + mySample, level: "error" });
                                return;
                            }
                        }
                        storeList[i] = [mySample,"New",submittedDateDef,,''];
                        var aliasLen = sampleAliasArray.length;
                        sampleAliasArray[aliasLen] = alias;
                        if ((i + 1) >= len) {
                            callback();
                        } else {
                            validateSamples(i + 1, sampleList, storeList, true, callback);
                        }
                    },
                    failure: function() {
                        Ext.MessageBox.alert("Sample does not exist:" + mySample);
                        eventManager.fireStatusMessageEvent({ text: "Sample does not exist:" + mySample, level: "error" });
                    }
                });
            }
        } else {
            var samples = Ext.getCmp('yseqSamples');
            storeList[i] = [samples.getValue(),"New",submittedDateDef,,''];
            callback();
        }
    }

    function standardSubmit() {
        if (Ext.getCmp('yseqType').getValue() == "RNASeq"){
            updateYSEQ(true);
            return;
        }
	//alert("standardSubmit returning, by passing java call");
	//return;
        var seqEntryPanel = Ext.getCmp('seqsamples-formid');
        var samples = Ext.getCmp('yseqSamples').getValue();
        var samplePrepCmp = Ext.getCmp("yseqSamplePrep");
        var samplePrepValue = samplePrepCmp.getValue();
        var sampleCountCmp = Ext.getCmp("yseqSampleCount");
        var indexMultiplex = samplePrepValue.indexOf("Multiplex");
        if (indexMultiplex != -1) {
            sampleCountCmp.setValue("1");
            var uploadFilename = Ext.getCmp('yseqRadSampleFileId').getValue();
            var splittedFile = uploadFilename.split("/");
            if (splittedFile != null && splittedFile.length > 1) {
                uploadFilename = splittedFile[splittedFile.length - 1];
            }
            var sampleFileTemplate = samples.replace(/ /g, "_") + ".csv";
            if (uploadFilename == null || uploadFilename.indexOf(sampleFileTemplate) == -1) {
                Ext.Msg.show({
                    title      : 'Validation Error',
                    msg        : "Uploaded RAD File " + uploadFilename + " is not " + sampleFileTemplate,
                    width      : 300,
                    buttons    : Ext.MessageBox.CANCEL,
                    icon       : Ext.MessageBox.ERROR
                });
                return false;
            }
        } else {
            var sampleAliasText = "";
            for (var i = 0; i < sampleAliasArray.length; i++)
            {
                sampleAliasText = sampleAliasText + sampleAliasArray[i] + " ";
            }
            if (createNew) {
                var sampleCount = sampleAliasArray.length;
                sampleCountCmp.setValue(sampleCount);
            }
        }
        if (seqEntryPanel.getForm().isValid()) {
            if (seqEntryPanel.baseParams) {
                for (i in seqEntryPanel.baseParams) {
                    seqEntryPanel.add(
                    {  xtype:"hidden",
                        name:i,
                        value:seqEntryPanel.baseParams[i]
                    });
                }
                seqEntryPanel.doLayout();
            }
            Ext.getCmp("submitButtonId").setDisabled(true);
            seqEntryPanel.getForm().submit({
                clientValidation: true,
                url: '/dudley-lims/sequencing/submit',
                success: function(form, action) {
                    Ext.Msg.alert('Success', action.result.msg);
                    document.location = "/dudley-lims/browser.html";
                },
                failure: function(form, action) {
                    switch (action.failureType) {
                        case Ext.form.Action.CLIENT_INVALID:
                            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                            break;
                        case Ext.form.Action.CONNECT_FAILURE:
                            Ext.Msg.alert('Failure', 'Ajax communication failed');
                            break;
                        case Ext.form.Action.SERVER_INVALID:
                            Ext.Msg.alert('Failure', action.result.msg);
                    }
                }
            });
        }
    }

    function updateYSEQ(create) {
        var yseqJson = new Object();
        var yseqKey = yseqHash.name;
        var yseqType = Ext.getCmp("yseqType").getValue();
        yseqJson["yseqKey"] = yseqKey;
        yseqJson["yseqState"] = yseqHash.yseqState;
        yseqJson["yseqDate"] = Ext.getCmp("yseqDate").getRawValue();
        yseqJson["yseqContact"] = Ext.getCmp("yseqContact").getRawValue();
        yseqJson["yseqReads"] = Ext.getCmp("yseqReads").getValue();
        yseqJson["yseqType"] = yseqType;
        yseqJson["yseqSizeSelection"] = Ext.getCmp("yseqSizeSelection").getValue();
        yseqJson["yseqStart"] = Ext.getCmp("yseqStart").getValue();
        yseqJson["yseqEnd"] = Ext.getCmp("yseqEnd").getValue();
        yseqJson["yseqProject"] = Ext.getCmp("yseqProject").getValue();
        yseqJson["yseqBudget"] = Ext.getCmp("yseqBudget").getValue();
        yseqJson["yseqNotes"] = Ext.getCmp("yseqNotes").getValue();
        yseqJson["yseqReadFormat"] = Ext.getCmp("yseqReadFormat").getValue();
        yseqJson["yseqRefGenome"] = Ext.getCmp("yseqRefGenome").getValue();
        yseqJson["yseqSamplePrep"] = Ext.getCmp("yseqSamplePrep").getValue();
        yseqJson["yseqAdaptorKit"] = Ext.getCmp("yseqAdaptorKit").getValue();
        yseqJson["yseqSlider"] = Ext.getCmp("yseqSlider").getValue();
        yseqJson["yseqShearMethod"] = Ext.getCmp("yseqShearMethod").getValue();
        yseqJson["yseqMultiplexDegree"] = Ext.getCmp("yseqMultiplexDegree").getValue();
        yseqJson["yseqPrimer"] = Ext.getCmp("yseqPrimer").getValue();
        yseqJson["yseqSamples"] = Ext.getCmp("yseqSamples").getValue();
        /*if (yseqJson["yseqSamples"] == undefined || yseqJson["yseqSamples"] == ""){
            Ext.Msg.alert('Error', 'Samples field is empty');
            return;
        }*/
        yseqJson["yseqSampleAlias"] = Ext.getCmp("yseqSampleAlias").getValue();
        var inst = Ext.getCmp("yseqInstrument").getValue();
        yseqJson["yseqInstrument"] = inst;
        if (inst == "SOLiD") {
            yseqJson["yseqNFSSolid"] = Ext.getCmp("yseqNFSSolid").getValue();
            yseqJson["yseqSolidBeadKit"] = Ext.getCmp("yseqSolidBeadKit").getValue();
        }
        if (yseqType == "RNASeq") {
            yseqJson["yseqRNAFraction"] = Ext.getCmp("yseqRNAFraction").getValue();
            yseqJson["yseqRNAStrandSpec"] = Ext.getCmp("yseqRNAStrandSpec").getValue();
            yseqJson["yseqRNABCModules"] = Ext.getCmp("yseqRNABCModules").getValue();
            yseqJson["yseqRNANFS"] = Ext.getCmp("yseqRNANFS").getValue();
        }
	yseqJson["yseqFastqc"] = Ext.getCmp("yseqFastqc").getValue();
	yseqJson["yseqBamSam"] = Ext.getCmp("yseqBamSam").getValue();

        var yseqUpdateCallback = function() {
            limsadmin_obj["limsadminYseqCount"] = yseqCount;
            postSolrUpdates(limsadmin_obj, function(){
                eventManager.fireStatusMessageEvent({ text: "New RNASeq Added Successfully", level: "info" });
                Ext.Msg.alert('Info', "New RNASeq " + yseqKey + ' Added Successfully');
            });
        };
        if (!create) {
            yseqUpdateCallback = function() {
                Ext.Msg.alert('Info', yseqKey + ' Updated Successfully');
                var searchResultsButton = Ext.getCmp("showYseqSearchResultsId");
                searchResultsButton.disable();
            };
        }
        postSolrUpdates(yseqJson, yseqUpdateCallback);
    }

    function loadEntryForm(entryHash, sampleArray, callback) {
        Ext.QuickTips.init();
        createNew = true;
        yseqCount = parseInt(yseqCount) + 1;
        var samplesReadOnly = false;
        var solidCollapsed = true;
        var rnaCollapsed = true;
        var radFileLabel = "CSV File (RAD Only)";
        if (entryHash == null) {
            yseqHash = new Object();
            yseqHash.name = 'YSEQ' + yseqCount;
            yseqHash.alignmentStart = "1";
            yseqHash.alignmentEnd = "36";
            yseqHash.contactEmail = LoggedInUser.userUri.split("/users/")[1];//email;
            yseqHash.yseqDate = submittedDateDef;
            yseqHash.readFormat = "Single";
            yseqHash.refGenome = 'Yeast S288C';
            yseqHash.dudleyProject = "Dudley Natural Variation";
            yseqHash.yseqType = "DNA";
            yseqHash.yseqSizeSelection = "N/A";
            yseqHash.samplePrep = "Genomic DNA";
            yseqHash.yseqState = "New";
            yseqHash.budget = "21200303";
            yseqHash.instrument = "Illumina";
            yseqHash.shearMethod = 'Covaris';
            yseqHash.adaptorKit = 'Illumina Genomic';
            yseqHash.multiplexDegree = "1";
            yseqHash.primer = 'Genomic DNA Sequencing Primer';
            yseqHash.slider = '1/8';
            yseqHash.yseqSolidBeadKit = 'N/A';
            yseqHash.yseqRNAFraction = 'N/A';
            yseqHash.yseqRNAStrandSpec = 'N/A';
            yseqHash.yseqRNABCModules = 'N/A';
            yseqHash.nfs_solid = solidNFSPath + "/"+yseqHash.name;
            yseqRNANFS = rnaNFSPath + "/"+yseqHash.name;
            var mydate = new Date();
            var theyear = mydate.getFullYear();
            var themonth = mydate.getMonth() + 1;
            var thetoday = mydate.getDate();
            yseqHash.yseqDate = themonth + "/" + thetoday + "/" + theyear;
            loadSampleGrid("", ds, createNew);
        } else {
            yseqHash = entryHash;
            if (yseqHash.instrument == "SOLiD") {
                solidCollapsed = false;
            }
            if (yseqHash.yseqType == "RNASeq") {
                rnaCollapsed = false;
            }
            createNew = false;
            samplesReadOnly = true;
            if (sampleArray != null) {
                var mySampleData = [];
                var si = 0;
                for (var i = 0; i < sampleArray.length; i++) {
                    var isPostedFile = sampleArray[i].isFile;
                    if (!isPostedFile) {
                        mySampleData[si] = translateSeqSampleResultJsonToArray(sampleArray[i]);
                        si = si + 1;
                    }
                }
                ds.loadData(mySampleData);
                loadSampleGrid(yseqHash.name, ds, createNew);
            }
            var samplePrep = entryHash.samplePrep;

            if (samplePrep.indexOf("RAD") != -1) {
                var sampleName = yseqHash.samples;
                sampleName = sampleName.toUpperCase();
                sampleName = sampleName.replace(/ /g, "_");
                radFileLabel = "/addama-rest/dudley-sample/path/datasource/YSEQ/" + yseqHash.name + "/" + sampleName + ".csv";
                radFileLabel = "<a href='" + radFileLabel + "' target='_blank'>View RAD Sample File" + "</a>";
            }
        }
        var updateDisabled = true;
        var createDisabled = false;
        if (!createNew) {
            createDisabled = true;
            updateDisabled = false;
        }
        var buttons = [
            {
                id: 'submitButtonId',
                name: 'submitButton',
                disabled: createDisabled,
                text: "Create",
                listeners: {
                    click: function() {
                        Ext.Msg.confirm('Message', "Confirm that you want to submit this job - after confirmation, a status email will be sent", function(btn) {
                            if (btn == 'yes') {
                                standardSubmit();
                            }
                        });
                    },
                    render: function(c) {
                        Ext.QuickTips.register({
                            target: c,
                            title: '',
                            text: 'Submits job to sequencing facility'
                        });
                    }
                }
            },
            {
                id: 'updateButtonId',
                text: 'Update',
                disabled: updateDisabled,
                listeners: {
                    click: function() {
                        updateYSEQ(false);
                    }
                }
            },
        ];

        var radVersionCombo = new Ext.form.ComboBox({
            store: radVersionStore,
            id: 'radVersionId',
            displayField:'value',
            valueField:'key',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            fieldLabel: 'RAD Version',
            value:"rad.1",
            forceSelection:true,
            selectOnFocus:true,
            listeners: {
                render: function(c) {
                    Ext.QuickTips.register({
                        target: c,
                        title: '',
                        text: 'Indicates RAD Version (1/Solexa .. 4/Solid)'
                    });
                    /*var querySql = "select well_pos, barcode where version = 'rad.1'";
                     var query = new google.visualization.Query("/google-dsapi-svc/addama/datasources/omics/rad_primer_barcode/query?tq=" + querySql);
                     query.send(function(response) {
                     radBarcodeJson = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());

                     if (response.isError()) {
                     Ext.Msg.alert("warning", "Contact Jake: Error at retrieving omics data for cgs query:" + querySql + "<br>" + response.getMessage());
                     return;
                     }
                     });*/
                }
            }
        });
        radVersionCombo.on("select", function (c, r, i) {
            var version = r.data.key.toLowerCase();
            alert("need to update code to get barcodes:" + version);
        });

        entryForm = new Ext.form.FormPanel({
            id: 'seqsamples-formid',
            frame:true,
            autoScroll: true,
            title: 'Sequencing Form Status:' + yseqHash.yseqState,
            bodyStyle:'padding:5px 5px 0',
            width: 700,
            height: 500,
            method: 'POST',
            fileUpload : true,
            buttonAlign: 'left',
            tbar:[
                {
                    id: 'detailSpotlightYCRId',
                    disabled: updateDisabled,
                    text: 'Spotlight',
                    icon: "images/add-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Add to spotlight',
                    listeners: {
                        click: function() {
                            var selectedArray = [yseqHash.name, yseqHash.name, yseqHash.samples];
                            sptlght.utils.SpotlightUtils.setSelectedRecord(selectedArray);
                            sptlght.utils.SpotlightUtils.setSource("yseq");
                            sptlght.utils.SpotlightUtils.handleAddToSpotlight();
                        }
                    }
                },
                {
                    id: 'generateRADCSVId',
                    disabled: !createNew,
                    text: 'GenerateRADBarcodeCSV',
                    icon: "images/star.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Generates csv',
                    listeners: {
                        click: function() {
                            var querySql = "select well_pos, barcode where version = 'rad.1'";
                            var query = new google.visualization.Query("/google-dsapi-svc/addama/datasources/omics/rad_primer_barcode/query?tq=" + querySql);
                            query.send(function(response) {
                                if (response.isError()) {
                                    Ext.Msg.alert("warning", "Try refreshing at database, try refreshing, if error persists contact Jake: Error at retrieving omics data for cgs query:" + querySql + "<br>" + response.getMessage());
                                    return;
                                }
                                radBarcodeJson = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
                                promptRadWin = new Ext.Window({
                                    title: 'Rad2CSV - Select columns',
                                    width: 480,
                                    height: 350,
                                    autoScroll: true,
                                    modal: true,
                                    bodyStyle: 'padding:2px;',
                                    items: [
                                        new Ext.form.FieldSet({
                                            autoHeight: true,
                                            border: false,
                                            items: [
                                                radVersionCombo,
                                                new Ext.form.NumberField({
                                                    fieldLabel: 'Total Number of Strains',
                                                    id: 'radStrainNum',
                                                    value: 48,
                                                    width: 200,
                                                    listeners: {
                                                        render: function(c) {
                                                            Ext.QuickTips.register({
                                                                target: c,
                                                                title: '',
                                                                text: 'Required integer: Total Number of strains in RAD submission'
                                                            });
                                                        }
                                                    }
                                                }),
                                                new Ext.form.NumberField({
                                                    fieldLabel: 'Progeny Key Start',
                                                    id: 'radStrainStart',
                                                    value: '',
                                                    width: 200,
                                                    listeners: {
                                                        render: function(c) {
                                                            Ext.QuickTips.register({
                                                                target: c,
                                                                title: '',
                                                                text: 'Required integer: Beginning YPG Key, ie 1'
                                                            });
                                                        },
                                                        change: function(t, n, o) {
                                                            var range = parseInt(n) + parseInt(Ext.getCmp("radStrainNum").getValue());
                                                            var ypgValError = false;
                                                            for (var r = parseInt(n); r < range; r++) {
                                                            //replace with SOLR
								var resourceUri = getSolrSearchUrl(getLuceneTerm("ypgKey","YPG" + r), 1, ypgFields);;
                                                                //var resourceUri = "/addama-rest/dudley-sample/path/datasource/YPG/YPG " + r + "/annotations";
                                                                Ext.Ajax.request({
                                                                    url: resourceUri,
                                                                    method: "GET",
                                                                    success: function(response) {
									                                var respText = Ext.util.JSON.decode(response.responseText);
	                                                                var ypgjson  = respText.response.docs[0];
                                                                        //var ypgjson = Ext.util.JSON.decode(response.responseText);
                                                                        rangeYPGJson[ypgjson.ypgKey] = ypgjson.ypgBoxNumber + "|" + ypgjson.ypgPosition + "|" + ypgjson.ypgTetrad;
                                                                        if (rangeYPGJson[ypgjson.ypgKey]) {
                                                                            Ext.getCmp("automateLayoutButtonId").setDisabled(false);
                                                                        } else {
                                                                            ypgValError = true;
                                                                            Ext.Msg.alert("warning", "Problem resolving YPG :" + ypgjson.ypgKey);
                                                                        }
                                                                    },
                                                                    failure: function() {
                                                                        alert("failed retrieving " + resourceUri);
                                                                        Ext.getCmp("automateLayoutButtonId").setDisabled(true);
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    }
                                                }),
                                                new Ext.form.NumberField({
                                                    fieldLabel: 'Cross Key Number',
                                                    id: 'radCrossKey',
                                                    value: '',
                                                    width: 200,
                                                    listeners: {
                                                        render: function(c) {
                                                            Ext.QuickTips.register({
                                                                target: c,
                                                                title: '',
                                                                text: 'Required: Valid entries are 5 (Vida), 6 (Michelle), ...'
                                                            });
                                                        },
                                                        change: function(t, n, o) {
                                                            var resourceUri = getSolrSearchUrl(getLuceneTerm("ycrKey","YCR" + n), 1, ycrFields);
                                                            Ext.Ajax.request({
                                                                url: resourceUri,
                                                                method: "GET",
                                                                success: function(response) {
                                                                    var respText = Ext.util.JSON.decode(response.responseText);
                                                                    radYcrJson = respText.response.docs[0];
                                                                    Ext.getCmp("radParentA").setValue(radYcrJson.ycrParentA);
                                                                    Ext.getCmp("radParentAlpha").setValue(radYcrJson.ycrParentAlpha);
                                                                    var begin = parseInt(radYcrJson.ycrProgenyRange.split("-")[0]);
                                                                    var end = parseInt(radYcrJson.ycrProgenyRange.split("-")[1]);
                                                                    var enteredStart = parseInt(Ext.getCmp("radStrainStart").getValue());
                                                                    var enteredEnd = enteredStart + parseInt(Ext.getCmp("radStrainNum").getValue());
                                                                    if (enteredStart < begin || enteredEnd > end) {
                                                                        alert("Progeny start/end keys must be in cross range:" + begin + "-" + end);
                                                                        Ext.getCmp("automateLayoutButtonId").setDisabled(true);
                                                                    }
                                                                },
                                                                failure: function() {
                                                                    alert("failed retrieving " + resourceUri);
                                                                }
                                                            });
                                                        }
                                                    }
                                                }),
                                                new Ext.form.TextField({
                                                    fieldLabel: 'Parent A',
                                                    id: 'radParentA',
                                                    value: '',
                                                    width: 200
                                                }),
                                                new Ext.form.TextField({
                                                    fieldLabel: 'Parent Alpha',
                                                    id: 'radParentAlpha',
                                                    value: '',
                                                    width: 200
                                                }),
                                                {
                                                    xtype:'checkbox',
                                                    fieldLabel: 'Include Parents',
                                                    labelSeparator: '',
                                                    checked: true,
                                                    id: 'includeParents',
                                                    listeners: {
                                                        render: function(c) {
                                                            Ext.QuickTips.register({
                                                                target: c, title: '', text: 'Checked means parents will be on sequencing plate'
                                                            });
                                                        }
                                                    }
                                                }

                                            ]
                                        })],
                                    buttons: [
                                        {
                                            text: 'Cherry Pick/Manual Layout',
                                            id: 'manualLayoutButtonId',
                                            handler: function() {
                                                loadRadPrimerLayout("Manual");
                                            }
                                        },
                                        {
                                            text: 'Automate Layout',
                                            id: 'automateLayoutButtonId',
                                            disabled: true,
                                            handler: function() {
                                                loadRadPrimerLayout("Auto");
                                            }
                                        }
                                    ],
                                    layout: 'fit'
                                });
                                promptRadWin.show();
                            });
                        }
                    }
                }
            ],
            buttons: buttons,
            items: [
                {
                    layout:'column',
                    items:[
                        {
                            columnWidth:.5,
                            layout: 'form',
                            items: [
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Job Key',
                                    id: 'yseqKey',
                                    value: yseqHash.name,
                                    allowBlank:false,
                                    anchor:'95%',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'System generated, this is an unique key that will identify this sequence job'
                                            });
                                        }
                                    }
                                },
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Budget number',
                                    id: 'yseqBudget',
                                    value: yseqHash.budget,
                                    anchor:'95%',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Budget number, see Teresa/Cathy/Jake if you need help'
                                            });
                                        }
                                    }
                                }
                            ]
                        },
                        {
                            columnWidth:.5,
                            layout: 'form',
                            items: [
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Contact email',
                                    id: 'yseqContact',
                                    value: yseqHash.contactEmail,
                                    anchor:'95%',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Default to be logged in user email'
                                            });
                                        }
                                    }
                                },
                                new Ext.form.DateField({
                                    id: "yseqDate",
                                    fieldLabel: "Date created",
                                    name: "yseqDate",
                                    value: yseqHash.yseqDate,
                                    size: 20,
                                    allowBlank: true
                                })
                            ]
                        },
                        {
                            columnWidth:.5,
                            layout: 'form',
                            items: [
                                getSeqTypeCombo(yseqHash),
                                getDudleyProjectCombo(yseqHash),
                                getInstrumentCombo(yseqHash),
                                getRefGenomeCombo(yseqHash),
                                getPrimerCombo(yseqHash),
                                getShearMethodCombo(yseqHash),
                                getAdaptorKitCombo(yseqHash)
                            ]
                        },
                        {
                            columnWidth:.5,
                            layout: 'form',
                            items: [
                                getSizeSelectionCombo(yseqHash),
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Alignment start',
                                    id: "yseqStart",
                                    anchor:'95%',
                                    value: yseqHash.alignmentStart,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Alignment start position defaults to 1. For RAD/multiplex, it is 5, or (1 + lengthOfRestrictionEnzypeSeq)'
                                            });
                                        },
                                        change: function(t, n, o) {
                                            var instrument = Ext.getCmp("yseqInstrument").getValue();
                                            if (instrument == "SOLiD" && (readLen != 35 || readLen != 50)) {
                                                Ext.Msg.alert("Read Length must be 35 or 50 for SOLiD platform");
                                                Ext.getCmp("yseqReads").setValue("35");
                                            }
                                        }
                                    }
                                },
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Alignment end',
                                    id: "yseqEnd",
                                    anchor:'95%',
                                    value: yseqHash.alignmentEnd,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Alignment End Position: legit values are 36, 72, for RAD, it is startPos + read length '
                                            });
                                        },
                                        change: function(t, n, o) {
                                            var readLen = parseInt(n) - parseInt(Ext.getCmp("yseqStart").getValue());
                                            Ext.getCmp("yseqReads").setValue(n);
                                            var instrument = Ext.getCmp("yseqInstrument").getValue();
                                            if (instrument == "SOLiD" && (readLen != 35 || readLen != 50)) {
                                                Ext.Msg.alert("Read Length must be 35 or 50 for SOLiD platform");
                                                Ext.getCmp("yseqReads").setValue("35");
                                            }
                                        }
                                    }
                                },
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Reads desired',
                                    id: 'yseqReads',
                                    anchor:'95%',
                                    value: '36',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Desired number of reads/cycles: 36, 72, 35 and 50 for SOLiD'
                                            });
                                        },
                                        change: function(t, n, o) {
                                            Ext.getCmp("yseqEnd").setValue(n);
                                            var instrument = Ext.getCmp("yseqInstrument").getValue();
                                            if (instrument == "SOLiD" && (n != "35" || n != 50)) {
                                                Ext.Msg.alert("Read Length must be 35 or 50 for SOLiD platform");
                                                Ext.getCmp("yseqReads").setValue("35");
                                            }
                                        }
                                    }
                                },
                                getReadFormatCombo(yseqHash),
                                getSamplePrepCombo(yseqHash),
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Samples per lane',
                                    id: "yseqMultiplexDegree",
                                    value: yseqHash.multiplexDegree,
                                    anchor:'95%',
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Multiplex degree represents the number of samples in a sequencing run'
                                            });
                                        }
                                    }
                                }
                            ]
                        }
                    ]
                },
		{
                	xtype:'textfield',
                        fieldLabel: 'SAM/BAM',
                        id: "yseqBamSam",
                        value: yseqHash.yseqBamSam,
                        anchor:'95%',
                        listeners: {
                        	render: function(c) {
                                	Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'SAM/BAM value updated from server script'
                                        });
                                }
                        }
                },
		{
                            xtype:'htmleditor',
                            id:'yseqFastqc',
			    value: yseqHash.yseqFastqc,	
                            //value: '<a href="http://www.w3schools.com/" target="_blank">Data</a>&nbsp;<a href="http://www.w3schools.com/" target="_blank"> HTML Report</a>',
                            fieldLabel:'FastQC Reports',
                            height:100,
                            anchor:'98%'
                 },
                new Ext.form.TextArea({
                    id: "yseqNotes",
                    fieldLabel: "Notes(strains, conditions, extraction, etc)",
                    name: "yseqNotes",
                    value: yseqHash.yseqNotes,
                    width: 500,
                    height: 40,
                    allowBlank: true,
                    listeners: {
                        render: function(c) {
                            Ext.QuickTips.register({
                                target: c,
                                title: '',
                                text: 'Sequencing Notes: #, &, %, @, and single/double quotes are not allowed, max length 30'
                            });
                        },
                        change: function(t, n, o) {
                            var washed = replacedIllegalEntries(n);
                            t.setValue(washed);
                        }
                    }
                }),
                {
                    xtype: 'fieldset',
                    id: 'solidparameters',
                    title: 'SOLiD Parameters',
                    width: 605,
                    collapsed: solidCollapsed,
                    collapsible: true,
                    items: [
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'Slider',
                            msgTarget: 'under',
                            items: [
                                getSliderTypeCombo(yseqHash)
                            ]
                        },
                        getEZBeadCombo(yseqHash),
                        new Ext.form.TextField({
                            id: "yseqNFSSolid",
                            fieldLabel: "NFS Path",
                            value: yseqHash.nfs_solid,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Long term storage path for Kerry'
                                    });
                                }
                            }
                        })
                    ]
                },
                {
                                    xtype: 'fieldset',
                                    id: 'rnaparameters',
                                    title: 'RNASeq Parameters',
                                    width: 605,
                                    collapsed: rnaCollapsed,
                                    collapsible: true,
                                    items: [
                                        {
                                            layout: 'hbox',
                                            width: 500,
                                            fieldLabel: 'RNAFraction',
                                            msgTarget: 'under',
                                            items: [
                                                getRNAFractionCombo(yseqHash)
                                            ]
                                        },
                                        new Ext.form.TextField({
                                            id: "yseqRNAStrandSpec",
                                            fieldLabel: "cDNA synthesis/Strand specificity",
                                            value: yseqHash.yseqRNAStrandSpec,
                                            width: 500,
                                            allowBlank: true
                                        }),
                                        new Ext.form.TextField({
                                            id: "yseqRNABCModules",
                                            fieldLabel: "SOLiD Barcoding Kit Modules",
                                            value: yseqHash.yseqRNABCModules,
                                            width: 500,
                                            allowBlank: true
                                        }),
                                        new Ext.form.TextField({
                                            id: "yseqRNANFS",
                                            fieldLabel: "NFS Path",
                                            value: yseqHash.yseqRNANFS,
                                            width: 500,
                                            allowBlank: true,
                                            listeners: {
                                                render: function(c) {
                                                    Ext.QuickTips.register({
                                                        target: c,
                                                        title: '',
                                                        text: 'Long term RNASeq storage path for Kerry'
                                                    });
                                                }
                                            }
                                        })
                                    ]
                },
                {
                    xtype:'textarea',
                    fieldLabel: 'Samples' + '<br><A HREF="javascript:popupPNGLayout(\'RAD4b\')">RAD4_BC_Map</A>' ,
                    readOnly: samplesReadOnly,
                    labelSeparator: '',
                    id: 'yseqSamples',
                    value: yseqHash.samples,
                    width: 500,
                    height: 20,
                    name: 'yseqSamples',
                    listeners: {
                        change: function(e1, nv, ov) {
                            if (nv != null && nv != "") {
                                Ext.getCmp("yseqSamples").setValue(nv.toUpperCase());
                                var newSampleList = nv.split(" ");
                                sampleAliasArray.length = 0;
                                var seqState = yseqHash.yseqState;
                                if (seqState == 'New' || seqState == 'Draft') {
                                    initData = [];
                                    validateSamples(0, newSampleList, initData, true, function () {
                                        ds.loadData(initData);
                                        loadSampleGrid(yseqHash.name, ds, createNew);
                                        var sampleAliasText = "";
                                        for (i = 0; i < sampleAliasArray.length; i++)
                                        {
                                            sampleAliasText = sampleAliasText + sampleAliasArray[i] + " ";
                                        }
                                        var samplesAliasField = Ext.getCmp("yseqSampleAlias");
                                        samplesAliasField.setValue(sampleAliasText);
                                    });
                                }
                            }
                        },
                        render: function(c) {
                            Ext.QuickTips.register({
                                target: c,
                                title: '',
                                text: 'Samples neet to exist in LIMS system, contact Jake if a sequencing job involving nonLIMS samples need to be submitted. <br>Enter in sample keys follow by comma, such as YO 1,YPG 2,YO 2... - NonRAD/Multiplex Samples, those samples need to be uploaded in a file.'
                            });
                        }
                    }
                },
                {
                    xtype:'textfield',
                    fieldLabel: radFileLabel,
                    id: "yseqRadSampleFileId",
                    disabled: true,
                    defaultAutoCreate : {tag:"input", enctype:"multipart/form-data", type:"file", size: "70", autocomplete: "off"},
                    listeners: {
                        render: function(c) {
                            Ext.QuickTips.register({
                                target: c,
                                title: '',
                                text: 'Field is disabled unless multiplex is selected; takes in CSV File that lists RAD samples, in this format - SampleKey,Tag,Seq'
                            });
                        }
                    }
                },
                sampleGrid,
                new Ext.form.TextArea({
                    id: "yseqSampleAlias",
                    fieldLabel: "Samples Aliases",
                    value: yseqHash.samplesAlias,
                    width: 500,
                    height: 50,
                    allowBlank: true,
                    listeners: {
                        render: function(c) {
                            Ext.QuickTips.register({
                                target: c,
                                title: '',
                                text: 'Samples Alias: Prepopulated: #, &, %, @, and double quotes are not allowed'
                            });
                        }
                    }
                }),
                {
                    xtype:'textfield',
                    id: "yseqState",
                    value: yseqHash.yseqState,
                    hidden: true
                },
                {
                    xtype:'textfield',
                    id: "saveAsDraftId",
                    hidden: true
                },
                {
                    xtype:'textfield',
                    id: "yseqSampleCount",
                    value: yseqHash.sampleCount,
                    hidden: true
                },
                {
                    xtype:'textfield',
                    id: "postToSlimSeqOnly",
                    hidden: true
                }
            ]
        });
        callback();
    }

    function loadRadPrimerLayout(type) {
        var RADStrain = Ext.data.Record.create([
            {
                name: 'count',
                type: 'float'
            },
            {
                name: 'name',
                type: 'string'
            },
            {
                name: 'barcode_index',
                type: 'float'
            },
            {
                name: 'barcode',
                type: 'string'
            },
            {
                name: 'plate',
                type: 'string'
            },
            {
                name: 'position',
                type: 'string'
            },
            {
                name: 'tetrad',
                type: 'string'
            }
        ]);
        var genData = function() {
            var includeParents = Ext.getCmp("includeParents").getValue();
            var wells = parseInt(Ext.getCmp("radStrainNum").getValue());
            var start = parseInt(Ext.getCmp("radStrainStart").getValue());
            var parentA = radYcrJson.ycrParentA;
            var parentAlpha = radYcrJson.ycrParentAlpha;
            initGenData = [];
            for (var i = 0; i < wells; i++) {
                var bc = radBarcodeJson[i].barcode;
                var ypgkey = start + i;
                var keyname = 'YPG' + ypgkey;
                var plate = rangeYPGJson[keyname].split("|")[0];
                var position = rangeYPGJson[keyname].split("|")[1];
                var tetrad = rangeYPGJson[keyname].split("|")[2];
                if (includeParents) {
                    if (i == wells - 2) {
                        keyname = parentA;
                        plate = "";
                        position = "";
                        tetrad = "";
                    } else if (i == wells - 1) {
                        keyname = parentAlpha;
                        plate = "";
                        position = "";
                        tetrad = "";
                    }
                }
                initGenData.push({
                    count : ypgkey - (start - 1),
                    name : keyname,
                    barcode_index : i + 1,
                    barcode : bc,
                    plate: plate,
                    position : position,
                    tetrad : tetrad
                });
            }
            return initGenData;
        };
        var genManualData = function() {
            var wells = parseInt(Ext.getCmp("radStrainNum").getValue());
            initGenData = [];
            for (var i = 0; i < wells; i++) {
                var bc = radBarcodeJson[i].barcode;
                var keyname = 'YPG';
                initGenData.push({
                    count : i + 1,
                    name : keyname,
                    barcode_index : i + 1,
                    barcode : bc,
                    plate: "",
                    position : "",
                    tetrad : ""
                });
            }
            return initGenData;
        };
        var store = {};
        if (type != 'Manual') {
            store = new Ext.data.GroupingStore({
                reader: new Ext.data.JsonReader({fields: RADStrain}),
                data: genData(),
                sortInfo: {field: 'count', direction: 'ASC'}
            });
        } else {
            store = new Ext.data.GroupingStore({
                reader: new Ext.data.JsonReader({fields: RADStrain}),
                data: genManualData(),
                sortInfo: {field: 'count', direction: 'ASC'}
            });
        }
        var radgrid = new Ext.grid.EditorGridPanel({
            store: store,
            width: 600,
            height: 500,
            autoScroll: true,
            region:'center',
            margins: '0 5 5 5',
            autoExpandColumn: 'name',
            clicksToEdit: 1,
            view: new Ext.grid.GroupingView({
                markDirty: false
            }),
            tbar: [
                {
                    icon: "images/add-green.png",
                    cls:'x-btn-text-icon',
                    text: 'Generate CSV',
                    handler: function() {
                        radwin.close();
                        promptRadWin.close();
                        var myitems = store.data.items;
                        var nextRadCount = parseInt(yseqRADCount) + 1;
                        var csvText = "";
                        for (var i = 0; i < myitems.length; i++) {
                            csvText = csvText + "YMULTI_RAD_" + nextRadCount + "," + myitems[i].data.plate + "," + myitems[i].data.position + "," + myitems[i].data.tetrad + "," + myitems[i].data.name + "," + myitems[i].data.barcode_index + "," + myitems[i].data.barcode + breakDelimiter;
                        }
                        export2Csv("YMULTI_RAD_" + nextRadCount + ".csv", csvText, "radbarcode2Csv");                       
                        Ext.Msg.alert("info", "YMULTI_RAD_" + nextRadCount + ".csv saving to downloads folder");

                    }
                }
            ],
            listeners: {
                afteredit: function(obj) {
                    var val = trim(obj.value);
                    var row = obj.row;
                    var bnStr = "ypgBoxNumber";
                    var posStr = "ypgPosition";
                    if (val.indexOf("Y") != -1) {
                        var resourceUri = getSolrSearchUrl("ypgKey:" + val, 1, ypgFields);
                        if (val.indexOf("YO") != -1){
                            resourceUri = getSolrSearchUrl("yoKey:" + val, 1, yoFields);
                            bnStr = "yoBoxNumber";
                            posStr = "yoPosition";
                        }else if (val.indexOf("YAD") != -1){
                            resourceUri = getSolrSearchUrl("yadKey:" + val, 1, yadFields);
                            bnStr = "yadBoxNumber";
                            posStr = "yadPosition";
                        }
                        Ext.Ajax.request({
                            url: resourceUri,
                            method: "GET",
                            success: function(response) {
                                store.removeAt(row);
                                var respText = Ext.util.JSON.decode(response.responseText);
                                var strainjson  = respText.response.docs[0];
                                var e = new RADStrain({
                                    count: row + 1,
                                    name: val,
                                    plate: strainjson[bnStr],
                                    barcode_index : row + 1,
                                    barcode: radBarcodeJson[row].barcode,
                                    position: strainjson[posStr],
                                    tetrad: strainjson.ypgTetrad
                                });
                                store.insert(row, e);
                            },
                            failure: function() {
                                alert("Invalid Sample: Key and URI used:" + resourceUri);
                            }
                        });
                    } else {
                        store.removeAt(row);
                        val = parseInt(val);
                        var e = new RADStrain({
                            count: row + 1,
                            name: obj.record.data.name,
                            plate: obj.record.data.plate,
                            barcode_index : val,
                            barcode: radBarcodeJson[val - 1].barcode,
                            position: obj.record.data.position,
                            tetrad: obj.record.data.tetrad
                        });
                        store.insert(row, e);
                    }
                }
            },
            columns: [
                {
                    id: 'count',
                    header: 'Count',
                    dataIndex: 'count',
                    width: 75,
                    sortable: true
                },
                {
                    id: 'name',
                    header: 'StrainKey',
                    dataIndex: 'name',
                    width: 120,
                    sortable: true,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: false
                    }
                },
                {
                    header: 'BC_index',
                    dataIndex: 'barcode_index',
                    width: 100,
                    sortable: true,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: false
                    }
                },
                {
                    header: 'Barcode',
                    dataIndex: 'barcode',
                    width: 100,
                    sortable: true
                },

                {
                    header: 'Plate',
                    dataIndex: 'plate',
                    width: 100,
                    sortable: true
                },
                {
                    id: 'position',
                    header: 'Position',
                    dataIndex: 'position',
                    width: 100,
                    sortable: true
                },
                {
                    id: 'tetrad',
                    header: 'Tetrad',
                    dataIndex: 'tetrad',
                    width: 100,
                    sortable: true
                }
            ]
        });
        var radwin = new Ext.Window({
            title: 'Strain Layout Grid',
            layout: 'border',
            autoScroll: true,
            layoutConfig: {
                columns: 1
            },
            width:650,
            height: 700,
            items: [radgrid]
        });
        radwin.show();
    }

    function loadSampleGrid(key, datastore, createNew) {
        var strain2BarcodeFlag = true;
        if (yseqHash != null && yseqHash.dudleyProject.indexOf("RAD") > -1 && yseqHash.yseqState != "New") {
            strain2BarcodeFlag = false;
        }
        var height = 200;
        var tbarButtons = [
            {
                id: 'csvButtonId',
                name: 'csvButton',
                disabled: false,
                text: 'CSV',
                icon: "images/check-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            var csvData = datastore.reader.arrayData;
                            var csvText = "yseqSampleKey,yseqSamples,yseqSampleStatus,yseqSampleStatusDate,yseqSampleFlowcell,yseqSampleLane,yseqSampleComments<br>";
                            csvData.sort(function(a, b) {
                                return a[0] > b[0];
                            });
                            for (var c = 0; c < csvData.length; c++) {
                                var cArray = csvData[c];
                                if (cArray[3] == null) {
                                    cArray[3] = "";
                                }
                                if (cArray[4] == null) {
                                    cArray[4] = "";
                                }
                                if (cArray[5] == null) {
                                    cArray[5] = "";
                                }                                
                                csvText = csvText + '"' + key + '_' + cArray[0] + '","' + cArray[0] + '","' + cArray[1] + '","' + cArray[2]
                                        + '","' + cArray[3] + '","' + cArray[4] + '","' + cArray[5] + '"<br>';
                            }
                            var area = {
                                xtype:'htmleditor',
                                id:'csvAreaSSamId',
                                value: csvText,
                                height:100,
                                anchor:'98%'
                            };
                            var ssamWin = new Ext.Window({
                                title: 'SeqSamples2CSV',
                                width: 500,
                                height: 500,
                                autoScroll: true,
                                modal: true,
                                bodyStyle: 'padding:2px;',
                                items: [area],
                                layout: 'fit'
                            });
                            ssamWin.show();
                        }
                }
            },
            {
                id: 'cgsButtonId',
                disabled: true,
                text: 'Create CGS',
                icon: "images/upload.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            selectedSeqRec["seqrun"] = yseqHash.name;
                            selectedSeqRec["project"] = yseqHash.dudleyProject;
                            var cgsPanel = Dudley.lims.YSEQCGS.getCGSPanelInst();
                            Dudley.lims.sequencingmgr.getOmicPanel().activate(cgsPanel);
                            Dudley.lims.YSEQCGS.loadNewYCGS(selectedSeqRec);
                        }
                }
            },
            {
                id: 'strain2BarcodeId',
                disabled: strain2BarcodeFlag,
                text: 'StrainBarcodes',
                icon: "images/multimarkers.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            var resourceUri = "/dudley-lims/sequencing/cgs/radtag2bc?seqkey=" + yseqHash.name + "&user=gcromie&password=cgs_s9bm!t";
                            Ext.Ajax.request({
                                url: resourceUri,
                                method: "GET",
                                success: function(response) {
                                    var respObj = Ext.util.JSON.decode(response.responseText);
                                    var csvText = "'strain'," + "'barcode'<br>";
                                    for (var j in respObj) {
                                        if (j.indexOf("YPG") != -1 || j.indexOf("YO") != -1 || j.indexOf("YAD") != -1) {
                                            csvText = csvText + j + "," + respObj[j] + "<br>";
                                        }
                                    }
                                    var ssamWin = new Ext.Window({
                                        title: 'Rad Strain Barcodes',
                                        width: 300,
                                        height: 700,
                                        autoScroll: true,
                                        modal: true,
                                        bodyStyle: 'padding:2px;',
                                        items: [
                                            {
                                                xtype:'htmleditor',
                                                id:'csvArea2BcId',
                                                value: csvText,
                                                height:100,
                                                anchor:'98%'
                                            }
                                        ],
                                        layout: 'fit'
                                    });
                                    ssamWin.show();
                                },
                                failure: function(response) {
                                    alert("failed on rest call for resource:" + resourceUri + "\n" + response);
                                }
                            });
                        }
                }
            }
        ];
        if (createNew) {
            height = 100;
            tbarButtons = [];
        } else {
            if (datastore.getTotalCount() == 0) {
                height = 100;
                tbarButtons = [];
            }
        }
        sampleGrid = {
            xtype: 'grid',
            ds: datastore,
            cm: colModel,
            sm: new Ext.grid.RowSelectionModel({
                singleSelect: true,
                listeners: {
                    rowselect: function(sm, row, rec) {
                        Ext.getCmp("seqsamples-formid").getForm().loadRecord(rec);
                    }
                }
            }),
            height: height,
            width: 500,
            autoScroll: true,
            id: 'sampleGridid-subjects',
            tbar: tbarButtons,
            labelSeparator: '',
            fieldLabel: 'Sample List<br>' + '<A HREF="javascript:popupPNGLayout(\'VIDA\')">Vida Plate Layout</A><br>'
                    + '<A HREF="javascript:popupPNGLayout(\'MICHELLE\')">Michelle Plate Layout</A>',
            border: true,
            listeners: {
                render: function(g) {
                    g.getSelectionModel().selectRow(0);
                },
                cellclick: function (g, ri, ci, e) {
                    selectedSeqRec["flowcell"] = g.getSelectionModel().getSelected().data.flowcell;
                    selectedSeqRec["lane"] = g.getSelectionModel().getSelected().data.lane;
                    selectedSeqRec["strain"] = g.getSelectionModel().getSelected().data.name;
                    var seqType = yseqHash.samplePrep;
                    if (seqType.indexOf("Multiplex") != -1) {
                        Ext.getCmp("multiplexButtonId").enable();
                    } else if (seqType.indexOf("Oligo") != -1) {
                        Ext.Message.alert("Oligo in construction");
                    } else {
                        Ext.getCmp("cgsButtonId").enable();
                    }
                }
            }
        };
        return sampleGrid;
    }

    function renderSequencingDetails(selectedRow, fromRptSelected) {
        var searchResultsButton = Ext.getCmp("showYseqSearchResultsId");
        if (searchResultsButton != null) {
            searchResultsButton.enable();
        }
        sequencingHash = new Object();

        if (selectedRow != null && fromRptSelected == 0) {
            populateSequencingJson(sequencingHash, selectedRow);
        } else {
            if (fromRptSelected == 0){
            	populateSingleSeqViaSearch(sequencingHash, mySequencingData[0]);
	   }else{
		populateSingleSeqViaSearch(sequencingHash, mySequenceData[fromRptSelected]);
	   }	
        }
        createNew = false;
        //SOLR
        var resourceUri = "/addama-rest/dudley-sample/path/datasource/YSEQ/" + sequencingHash.name;
        Ext.Ajax.request({
            url: resourceUri + "/search?FREE_TEXT=*&PROJECTION=flowcell&PROJECTION=lane&PROJECTION=sampleStatusDate&PROJECTION=sampleStatus&PROJECTION=comment",
            method: "GET",
            success: function(response) {
                //decode and get directories (indicates that there are children/samples
                var respObj = Ext.util.JSON.decode(response.responseText);
                var sampleArray = respObj.results;
                loadEntryForm(sequencingHash, sampleArray, function() {
                    sequencingFormRender();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Read only access allowed", level: "info" });
                loadEntryForm(sequencingHash, null, function() {
                    sequencingFormRender();
                });
            }
        });

    }

    // render the grid to the specified div in the page
    function renderSequencingSearchResult() {
        if (mySequencingData.length == 1) {
            renderSequencingDetails(null,0);
            return;
        }
        var searchResultsButton = Ext.getCmp("showYseqSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        var mytbar = [
            {
                id: 'seq2CSVId',
                text: 'Export2CSV',
                icon: "images/check-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Export search results to csv',
                listeners: {click:
                        function() {
                            Dudley.lims.YSEQEntry.toCSV();
                        }
                }
            },
	    {
                id: 'seqRptId',
                text: 'Status Report',
                icon: "images/hourglass.png",
                cls:'x-btn-text-icon',
                tooltip: 'Displays sequencing status of bam/sam, fastQC reports',
                listeners: {click:
                        function() {
    				var sstore = new Ext.data.ArrayStore({
        			fields: [
            				{ name: 'YSEQ', type: 'string' },
            				{ name: 'BamSam', type: 'string' },
	    				{ name: 'FastQc', type: 'string' }
        			],sortInfo: {field:'YSEQ', direction:'ASC'}
    				});
    sstore.loadData(seqRptArray);
    var rptgrid = new Ext.grid.GridPanel({
        store: sstore,
        loadMask: true,
        columns: [
            { header: 'YSEQ', dataIndex: 'YSEQ' },
            { header: 'BamSam', dataIndex: 'BamSam' },
	    { header: 'FastQc', dataIndex: 'FastQc' }
        ],
        viewConfig: {
            forceFit: true
        }
    });

    rptgrid.on("celldblclick", function (g, ri, ci, e) {
		renderSequencingDetails(g,ri);
		grptWin.close();    
    });

    grptWin = new Ext.Window({
        layout: 'fit',
	title: 'YSEQ Status',
        width: 400,
        height: 400,
	autoSroll: true,
        closable: true,
        buttonAlign: 'center',
        items: [rptgrid],
        modal: true
    });
    grptWin.show();
	}
                        }
            },
            {
                id: 'seqMsgId',
                text: 'Announcements',
                icon: "images/info.png",
                cls:'x-btn-text-icon',
                tooltip: 'Displays latest sequencing status announcements',
                listeners: {click:
                        function() {
                            var homepage = false;
                            loadAnnouncements(homepage);
                        }
                }
            }
        ];
        pagingBar = new Ext.PagingToolbar({
            pageSize: 10,
            store: sequencingStore,
            displayInfo: true,
            displayMsg: 'Displaying sequencing batches {0} - {1} of {2}',
            emptyMsg: "No batches to display"
        });

        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "sequencingSearchResultsId",
            store: sequencingStore,
            columns: getSequencingSearchColumnHeaders(),
            stripeRows: true,
            autoHeight: true,
            width: 800,
            title: 'Run Submissions',
            renderTo: "yseq-search-results",
            tbar: mytbar,
            bbar: pagingBar
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            renderSequencingDetails(g,0);
        });
        searchResultsGrid.on("rowcontextmenu", onMessageContextMenu);
    }

    function onMessageContextMenu(grid, rowIndex, e) {
        var activePage = Math.ceil((pagingBar.cursor + pagingBar.pageSize) / pagingBar.pageSize);
        var realIndex = (activePage - 1) * pagingBar.pageSize + rowIndex;
        sptlght.utils.SpotlightUtils.setSelectedRecord(sequencingStore.allData.items[realIndex].json);
        sptlght.utils.SpotlightUtils.setSource("yseq");
        e.preventDefault();
        e.stopEvent();
        var coords = e.getXY();
        spotlightMenu.showAt([coords[0], coords[1]]);
    }

    function sequencingFormRender() {
        var omicsPanel = Dudley.lims.sequencingmgr.getOmicPanel();
        omicsPanel.activate(entryPanel);
        Dudley.lims.sequencingmgr.clearPane();
        entryForm.render("wo-form");
    }

    function setYseqAdmin(jsonObj){
        	limsadmin_obj =  jsonObj;
            yseqHash = null;
            yseqCount = limsadmin_obj.limsadminYseqCount;
            yseqMaxNum = limsadmin_obj.limsadminYseqCount;
            yseqOligoCount = limsadmin_obj.limsadminYseqOligoCount;
            yseqRADCount = limsadmin_obj.limsadminYseqRADCount;
            loadEntryForm(yseqHash, [], function() {
                Ext.getDom("yseq-search-results").innerHTML = "";
                Ext.getDom("wo-form").innerHTML = "";
                entryForm.render("wo-form");
            });
         }

    // public
    return {
        initEntry: function(callback) {
            initYSEQStore(function() {
                renderSequencingSearchResult();
                callback();
            });
        },
        getEntryPanelInst: function() {
            return entryPanel;
        },
        getEntryPanel: function() {
            loadEntryPanel();
            return entryPanel;
        },
        setSeqData: function(seqData) {
            mySequencingData = seqData;
        },
        toCSV: function() {
            
            var csvText = "yseqKey,yseqDate,yseqState,yseqSampleCount,yseqReads,yseqProject,yseqContact,yseqBudget,yseqStart,yseqEnd," +
                          "yseqNotes,yseqReadFormat,yseqRefGenome,yseqSamplePrep,yseqSamples,yseqSampleAlias," +
                          "yseqInstrument,yseqAdaptorKit,yseqShearMethod,yseqMultiplexDegree,yseqKit,yseqSlider,yseqPrimer,yseqNFSSolid" + breakDelimiter;
            mySequencingData.sort(function(a, b) {
                return a[0] - b[0];
            });
            for (var c = 0; c < mySequencingData.length; c++) {
                var cArray = mySequencingData[c];
                var pline = "";
                for (var ci = 1; ci < cArray.length; ci++) {
                    if (cArray[ci] == undefined || cArray[ci] == null) {
                        cArray[ci] = "";
                    }
                    cArray[ci] = cArray[ci] + "";
                    cArray[ci] = cArray[ci].replace(/'/g, "");
                    cArray[ci] = '"' + cArray[ci] + '"';
                    cArray[ci] = cArray[ci].replace(/YCR /, "YCR");
                    cArray[ci] = cArray[ci].replace(/YPG /g, "YPG");
                    cArray[ci] = cArray[ci].replace(/YO /, "YO");
                    cArray[ci] = cArray[ci].replace(/YAD /, "YAD");
                    pline = pline + cArray[ci] + ",";
                }
                csvText = csvText + pline.substr(0, pline.length - 1) + breakDelimiter;                
            }
            export2Csv("YSEQSearchedResults.csv", csvText, "yseq2Csv");
        },
        setEntryLoaded: function(boo) {
            entryLoaded = boo;
        },
        setSearchParams: function(myParam, myOption) {
            searchInput = myParam;
            searchOption = myOption;
        },
        getEntryStore: function() {
            return null;
        },
        getEntryLoaded: function() {
            return entryLoaded;
        },
        loadGoSearch: function() {
            goSearch(0, searchInput, searchOption);
        },
        loadNewEntry: function() {
            Ext.getDom("wo-form").innerHTML = "";
            if (LoggedInUser.userUri == "/addama-users/users/public@systemsbiology.org") {
                Ext.Msg.alert("warning", "You not have permission to create new sequencing run submission");
            } else {
                   Ext.Msg.alert("warning", "Must use Chrome or Firefox 3.X (Firefox->About) for sequencing submits");
                   getSolrLimsAdmin(setYseqAdmin);
            }
        },
        loadEntryResult: function() {
            Ext.getDom("yseq-search-results").innerHTML = "";
        } ,
        setArrayData: function(data) {
                    mySequenceData = data;
         }
    };
}
();

